<template>
  <div class="setting-container">
    <div class="app-container">
      <el-card v-loading="loading">
        <el-tabs>
          <!-- 左侧 -->
          <el-tab-pane label="角色管理">
            <!-- 按钮 -->
            <el-button
              icon="el-icon-plus"
              size="small"
              type="primary"
              @click="showDialog = true"
              >新增角色</el-button
            >
            <!-- 表格 -->
            <el-table :data="list" style="width: 100%">
              <el-table-column
                type="index"
                :index="indexMethod"
                prop=""
                label="序号"
                width="200"
              />
              <el-table-column prop="name" label="角色名称" />
              <el-table-column prop="description" label="描述" />
              <el-table-column prop="" label="操作" width="400">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="text"
                    @click="handleAssign(scope.row.id)"
                    >分配权限</el-button
                  >
                  <el-button
                    size="small"
                    type="text"
                    @click="edit(scope.row.id)"
                    >编辑</el-button
                  >
                  <el-button size="small" type="text" @click="del(scope.row.id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
            <el-pagination
              :total="total"
              :current-page="page"
              :page-size="pagesize"
              :page-sizes="[1, 2, 3, 4, 5]"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              layout="total, sizes, prev, pager, next, jumper"
            >
            </el-pagination>
          </el-tab-pane>

          <el-tab-pane label="公司信息">
            <!-- 警告信息 -->
            <el-alert
              title="对公司名称、公司地址、营业执照、公司地区的更新，将使得公司资料被重新审核，请谨慎修改"
              type="info"
              show-icon
              :closable="false"
            />
            <!-- 表单 -->
            <el-form label-width="120px" style="margin-top: 50px">
              <el-form-item label="公司名称">
                <el-input
                  v-model="companyForm.name"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="公司地址">
                <el-input
                  v-model="companyForm.companyAddress"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="邮箱">
                <el-input
                  v-model="companyForm.mailbox"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="companyForm.remarks"
                  type="textarea"
                  :rows="3"
                  disabled
                  style="width: 400px"
                />
              </el-form-item>
            </el-form>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <el-dialog
        :title="dialogTitle"
        :visible="showDialog"
        :close-on-click-modal="false"
        @close="handleCloseDialog"
      >
        <el-form
          ref="roleForm"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入角色名称" />
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="form.description" placeholder="请输入角色描述" />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button type="primary" @click="clickSubmit">确认</el-button>
          <el-button @click="handleCloseDialog">取消</el-button>
        </template>
      </el-dialog>
      <!-- 分配权限的弹层 -->
      <el-dialog
        title="分配权限"
        :visible="showAssignDialog"
        @close="closeAssignDialog"
      >
        <el-tree
          ref="tree"
          node-key="id"
          show-checkbox
          check-strictly
          default-expand-all
          :data="permissionList"
          :props="{ label: 'name' }"
        />
        <template #footer>
          <div style="text-align: right">
            <el-button @click="closeAssignDialog">取消</el-button>
            <el-button type="primary" @click="clickAssignSubmit"
              >确定</el-button
            >
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {
  reqGetRoleList,
  reqDelRole,
  reqAddRole,
  reqGetRoleDetail,
  reqUpdateRole,
  reqAssignPermission,
} from "@/api/setting";
import { reqGetCompanyById } from "@/api/company";
import { reqGetPermissionList } from "@/api/permission";
import { TreeToList } from "@/utils";
import { mapState } from "vuex";
export default {
  name: "Settings",
  created() {
    this.getRoleList();
    this.getCompanyById();
  },
  data() {
    return {
      roleId: "", //角色ID
      showAssignDialog: false,
      showDialog: false,
      loading: false,
      page: 1,
      pagesize: 5,
      total: 0,
      list: [],
      permissionList: [],
      companyForm: {
        name: "",
        companyAddress: "",
        mailbox: "",
        remarks: "",
      },
      form: {
        name: "",
        description: "",
      },
      rules: {
        name: [
          {
            required: true,
            message: "角色名称不能为空",
            trigger: ["blur", "change"],
          },
        ],
        description: [
          {
            required: true,
            message: "角色描述不能为空",
            trigger: ["blur", "change"],
          },
        ],
      },
    };
  },
  computed: {
    ...mapState("user", ["userInfo"]),
    dialogTitle() {
      return this.form.id ? "编辑角色" : "新增角色";
    },
  },
  methods: {
    async clickAssignSubmit() {
      const permIds = this.$refs.tree.getCheckedKeys();
      const res = await reqAssignPermission(this.roleId, permIds);
      console.log(res);
      this.$message.success("分配权限成功");
      this.closeAssignDialog();
    },
    async handleAssign(id) {
      this.showAssignDialog = true;
      this.roleId = id;
      const { data } = await reqGetPermissionList();
      this.permissionList = TreeToList(data, "0");

      const {
        data: { permIds },
      } = await reqGetRoleDetail(id);
      this.$refs.tree.setCheckedKeys(permIds);
    },
    closeAssignDialog() {
      this.showAssignDialog = false;
      this.$refs.tree.setCheckedKeys([]);
    },
    async getCompanyById() {
      const { data } = await reqGetCompanyById(this.userInfo.companyId);
      this.companyForm = data;
    },
    async edit(id) {
      console.log(id, 777);
      const { data } = await reqGetRoleDetail(id);
      this.form = data;
      this.showDialog = true;
    },
    del(id) {
      console.log(id);
      this.$confirm("你确定要删除么？该操作不可逆", "温馨提示")
        .then(async () => {
          const res = await reqDelRole(id);
          console.log(res);
          this.$message.success("删除角色成功");
          if (this.list.length === 1 && this.page > 1) {
            this.page--;
          }
          this.getRoleList();
        })
        .catch(() => {
          console.log("取消");
        });
    },
    handleCurrentChange(val) {
      this.page = val;
      this.getRoleList();
    },
    handleSizeChange(val) {
      this.pagesize = val;
      this.page = 1;
      this.getRoleList();
    },
    async getRoleList() {
      this.loading = true;
      const {
        data: { total, rows },
      } = await reqGetRoleList(this.page, this.pagesize);
      this.list = rows;
      this.total = total;
      this.loading = false;
    },
    indexMethod(index) {
      return index + 1 + this.pagesize * (this.page - 1);
    },
    handleCloseDialog() {
      this.showDialog = false;
      this.$refs.roleForm.resetFields();
      this.form = {
        name: "",
        description: "",
      };
    },
    clickSubmit() {
      this.$refs.roleForm.validate(async (flag) => {
        if (!flag) return;
        console.log("可以发请求了");
        if (this.form.id) {
          // 编辑
          const res = await reqUpdateRole(this.form);
          console.log(res);
          this.$message.success("编辑角色成功");
        } else {
          // 新增
          const res = await reqAddRole(this.form);
          console.log(res);
          this.$message.success("新增角色成功");
        }
        this.showDialog = false;
        this.getRoleList();
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.setting-container {
  ::v-deep.el-table__header-wrapper {
    .el-table__header {
      .cell {
        text-align: center;
      }
    }
  }
  ::v-deep.el-table__body-wrapper {
    div {
      text-align: center;
    }
  }
  .el-pagination {
    padding: 10px 5px 2px 5px;
    text-align: end;
  }
}
</style>